package com.test.mq;


import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Description
 * @Author xsd
 * @Date 2020/6/20
 */
public class MqQueCon {
    //1.连接工厂
    private ConnectionFactory factory;
    //2.连接对象
    private Connection connection;
    //3.Session对象
    private Session session;
    //4.生产者
    private MessageProducer producer;

    public MqQueCon(){
        try {
            factory=new ActiveMQConnectionFactory("tcp://120.92.88.22:61616");
            connection=factory.createConnection();
            connection.start();
            //自动 ack
            session=connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            producer=session.createProducer(null);
            //7.是否持久化 -不持久化,挂掉存磁盘-
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(){
        try {
//            Destination destination=session.createTopic("topic1");
            Destination destination=session.createQueue("que-1");
            TextMessage textMessage=session.createTextMessage("发布的测试消息");
            producer.send(destination,textMessage);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
    public void revice(){
        try {
            Destination destination=session.createTopic("top-1");
//            Destination destination=session.createQueue("que-1");  // 创建连接的消息队列
            MessageConsumer messageConsumer=session.createConsumer(destination); // 创建消息消费者
            //同步阻塞，异步非阻塞-监听
            while(true){
                TextMessage textMessage=(TextMessage)messageConsumer.receive(100000);
                if(textMessage!=null){
                    System.out.println("收到的消息："+textMessage.getText());
                }else{
                    break;
                }
            }
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        MqQueCon publish=new MqQueCon();
//        publish.send();
        publish.revice();
    }
}
